package com.vybfi.pma.controllers;

import com.vybfi.pma.dao.ProjectRepository;
import com.vybfi.pma.dao.StudentRepository;
import com.vybfi.pma.entities.Student;
import com.vybfi.pma.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("students")
public class StudentController {

    @Autowired
    StudentService studentService;


    @GetMapping()
    public String displayStudent(Model model){
        List<Student> students=studentService.getAll();
        model.addAttribute("students",students);
        return "students/list-students";
    }

    @GetMapping("/new")
    public String displayStudentForm(Model model){
        Student aStudent=new Student();
        model.addAttribute("student",aStudent);
        return "students/new-student";
    }

    @PostMapping("/save")
    public String createStudent(Model model, @Valid Student student, Errors errors){
        if (errors.hasErrors()) return "students/new-student";
        //将用户写入的表单存入数据库
        studentService.save(student);
        //防止重复提交-退回原网页？
        return "redirect:/students/new";
    }

    @GetMapping("/update")
    public  String displayStudentUpdateForm(@RequestParam("id") long theId , Model model){
        Student student = studentService.findByStudentId(theId);
        model.addAttribute("student",student);
        return "students/new-student";
    }

    @GetMapping("/delete")
    public  String DeleteStudent(@RequestParam("id") long theId , Model model){
        Student student = studentService.findByStudentId(theId);
        studentService.delete(student);
        model.addAttribute("student",student);
        return "students/new-student";
    }

}
